HTTP 与 HTTPS 详解
HTTP 和 HTTPS 是 Web 编程中最基础也最关键的通信协议。本页将以初学者角度介绍它们的原理、区别、使用场景及编程实战。
🌐 什么是 HTTP?
HTTP(HyperText Transfer Protocol)是一种用于客户端和服务器通信的协议,常用于网页数据的传输。
GET /api/user HTTP/1.1
Host: example.com
- 无状态:每次请求彼此独立
- 明文传输:任何中间人都能看到内容
🔓 HTTP 的风险
- 密码、表单内容等传输过程是明文
- 容易被中间人监听、篡改 、伪造
caution
因此在生产环境中必须避免使用 HTTP。
🔐 HTTPS 是什么?
HTTPS 是加密版的 HTTP,添加了 TLS(或旧称 SSL)加密层,保护数据安全。
HTTPS = HTTP + TLS(加密、安全握手)
🔐 HTTPS 如何加密通信?
握手流程(简化版)
- 客户端访问
https://example.com - 服务器返回数字证书(包含公钥)
- 客户端验证证书合法性
- 客户端用公钥加密一个对称密钥发给服务器
- 双方基于该密钥使用对称加密通信
✨ HTTP vs HTTPS 对比
| 项目 | HTTP | HTTPS |
|---|---|---|
| 加密 | ❌ 无 | ✅ 有 |
| 端口 | 80 | 443 |
| 证书支持 | ❌ | ✅ SSL/TLS 证书 |
| 安全性 | ❌ | ✅ |
🧑💻 编程实战场景
✅ 前端发起请求
- axios (JS/TS)
- fetch (JS)
import axios from 'axios';
axios.get("https://api.example.com/user")
.then(res => console.log(res.data));
fetch("https://yourdomain.com/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "123456" })
});
✅ 后端启用 HTTPS(Node.js 示例)
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('private.key'),
cert: fs.readFileSync('certificate.crt')
};
https.createServer(options, (req, res) => {
res.write("Hello HTTPS");
res.end();
}).listen(443);
✅ Python 请求 HTTPS 接口
import requests
res = requests.get("https://api.github.com")
print(res.status_code)
print(res.json())